package com.mjk.common.core.jdbc.service.idgenerator;

import cn.hutool.core.bean.BeanUtil;
import com.mjk.common.base.model.BaseEntity;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.core.jdbc.util.TableUtils;
import com.mjk.common.core.jdbc.util.provider.SqlProvider;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.ReflectionUtils;

/**
 * ID生成器
 */
public interface IdGenerator {
    /**
     * 获取主键信息
     *
     * @param entity
     * @return
     */
    String getId(BaseEntity entity);

    default String getKey(BaseEntity entity) {
        String key = SqlProvider.getPramaryKey(entity);
        String tableName = TableUtils.getTableName(entity);
        return tableName + "." + key;
    }

    default Integer getMaxId(BaseEntity entity) {
        String primary = SqlProvider.getPramaryKey(entity);
        BeeDBService service = BeeSpringBean.getBean(BeeDBService.class);
        BeeQueryWrapper wrapper = new BeeQueryWrapper(entity);
        wrapper.select("Max(" + primary + ") as " + primary);
        entity = (BaseEntity) service.findOneByWrapper(wrapper);
        Object value = BeanUtil.getFieldValue(entity, primary);
        try {
            return Integer.valueOf(value.toString()) + 1;//需要比最大值大1
        } catch (Exception e) {
            BizLogger.error(e);
            return 0;
        }
    }
}
